<?php
class Controller_BoNewsNotice extends Controller_Boprepare
{
    /**
     * 新闻信息(Create)
     */
    public function actionAddNews()
    {
        $Pnews_id     = isset($_POST['news_id'])   ? $_POST['news_id']         : NULL;
        $Ptitle       = isset($_POST['title'])     ? $_POST['title']           : NULL;
        $Pbody        = isset($_POST['body'])      ? $_POST['body']            : NULL;
        $Ppublisher   = isset($_POST['publisher']) ? $_POST['publisher']       : NULL;
        $Pcategory_id = isset($_POST['ctgry_id'])  ? $_POST['ctgry_id']        : 11;
        $Psticky      = isset($_POST['sticky']) && $_POST['sticky'] == 0 ? 0   : 1;
        $Ptag         = isset($_POST['tag'])       ? $_POST['tag']             : NULL;
        $Pisprivate   = isset($_POST['isprivate']) && $_POST['isprivate'] == 0 ? 0 : 1;

        $Payear  = isset($_POST['ayear'])  ? $_POST['ayear']  : NULL;
        $Pamonth = isset($_POST['amonth']) ? $_POST['amonth'] : NULL;
        $Paday   = isset($_POST['aday'])   ? $_POST['aday']   : NULL;

        $Fattachments = isset($_FILES['attachment']) ? TRUE : FALSE;

        if($Ptitle && $Pbody && $Ppublisher && $Pcategory_id) // 太长条件写不下，与里面的if'与'关系
        {
            if(News::find('title = ? AND category_id = ?', $Ptitle, $Pcategory_id)->query()->news_id == '')
            {

                /**
                 * 处理新闻发布时间
                 * 可以自定
                 * 将 2009-01-01 转换为服务器时间，请避开这个日期
                 */
                if(($Padate = "20{$Payear}-{$Pamonth}-${Paday}") == '2009-01-01')
                {
                    $Padate = date('Y-m-d', $_SERVER['REQUEST_TIME']);
                }

                /**
                 * 正常处理其他值
                 * 有必填的空
                 * 部分不是必须，有自动填充
             *
             * 先处理fckeditor 传进来的 body
                 */
            if(strpos($Pbody, '<div>') !== FALSE)
            {
               $Pbody = str_replace('<div>', '<p>', $Pbody);
            }
            if(strpos($Pbody, '</div>') !== FALSE)
            {
               $Pbody = str_replace('</div>', '</p>', $Pbody);
            }
            if(strpos($Pbody, '<br />') !== FALSE)
            {
               $Pbody = str_replace('<br />', '</p><p>', $Pbody);
            }
                $obj = new News(
                    array(
                        'title'       => $Ptitle,
                        'body'        => $Pbody,
                        'publisher'   => $Ppublisher,
                        'created'     => $_SERVER['REQUEST_TIME'], // 要求可改
                        'updated'     => $_SERVER['REQUEST_TIME'],
                        'adate'       => $Padate,                  // 手动添加的日期
                        'adated'      => strtotime($Padate),
                        'hasread'        => 1,
                        'category_id' => $Pcategory_id,
                        'tag'         => ','.$Ptag.',',
                        'sticky'      => $Psticky,
                        'isprivate'   => $Pisprivate,
                ));
                $obj->save();
            }

            /**
             * 有内容"提交"后
             * 如果有附件，处理附件，更新 $attachment
             *
             * 第一步，处理文件本身
             * 第二步，处理数据表
             *
             * ($Fattachments == TRUE) 表示有附件上传
             */
            if($Fattachments)
            {
                // 此为表逻辑操作，应当被封装为如下语句
                //$notice = $this->_tdocs->uploadAttachment($_param1, $paramN);

                /**
                 * 定义允许上传的文件类型
                 * 可在数据库修改
                 * 'jpg,png,gif, doc,docx,ppt,pptx,xsl,xslx, txt,pdf, rar,zip,tgz'
                 */
                $allowExts     = Q::ini('appini/uploadAllowExts');

                /**
                 * NOTICE : 该值与PHP设置 {php.ini} 有关
                 * 定义允许上传的最大尺寸
                 * 可在数据库修改
                 * 10 * 1024 * 1024 (10M)
                 */
                $maxSize       = Q::ini('appini/uploadMaxSize');

                /**
                 * 定义允许 课件文件夹
                 * '../upload_attachment'
                 */
                $attachmentDir = Q::ini('appini/attachmentDir');

                $uploader      = new Helper_Uploader();
                $attachments   = $uploader->allfiles();

                $news_id = News::find('title = ? AND category_id = ?', $Ptitle, $Pcategory_id)->query()->news_id;
                foreach($attachments as $attachment)
                {
                    // 执行操作：移动文件
                    $attachmentid = md5($_SERVER['REQUEST_TIME'] . $attachment->filename());
                    $filename = urlencode($attachmentid . '.' . strtolower($attachment->extname()));
                    $attachment->move($attachmentDir."/{$filename}");

                    // 执行操作：保存文件映射记录
                    $newAttachmentRecord = new NewsAttachment(
                        array(
                            'path'     => $attachmentDir."/{$filename}",
                            'size'     => round($attachment->filesize() / 1024 / 1024 , 2).'M',
                            'type'     => $attachment->extname(),
                            'filename' => $attachment->filename(),
                            'news_id'  => $news_id,
                    ));
                    $newAttachmentRecord->save();
                }

                // 处理 $alltags
                // 新闻通知版块是 ARRAY_MERGE getSubArray(4,7,8,23)
                $tag_category = NULL;
                if(in_array($Pcategory_id, NewsCategory::getSelfArrayId(array(4,7,8,23))) !== FALSE)
                {
                    $tag_category = '新闻通知';
                }
                elseif(in_array($Pcategory_id, NewsCategory::getSelfArrayId(81)) !== FALSE)
                {
                    $tag_category = '国际交流';
                }
                elseif(in_array($Pcategory_id, NewsCategory::getSelfArrayId(83)) !== FALSE)
                {
                    $tag_category = '创新实践';
                }

                if($tag_category != NULL && $Ptag != '')
                {
                    foreach(explode(',', $Ptag) as $v)
                    {
                        $obj = Tag::find('category = ? AND tag = ?', $tag_category, $v)->query();
                        if($obj->tag_id == '')
                        {
                            $obj->category     = $tag_category;
                            $obj->tag          = $v;
                            $obj->counts       = 1;
                            $obj->isvisible    = 1;
                            $obj->isonhomepage = 0;
                            $obj->hit_as_query = 0;
                            $obj->save();
                        }
                        else
                        {
                            $obj->counts += 1;
                            $obj->save();
                        }
                    }
                }

                // 显示列表
                return $this->_forward('bonewsnotice/listnews');
            }
        }

        $this->_view['cssfile'] = 'bonewsnotice.css';
    }
    /**
     * 新闻信息(Read)
     */
    public function actionListNews()
    {
        $Gctgry_id   = isset($_GET['ctgry_id'])   ? (int)$_GET['ctgry_id'] : NULL;
        $Gpage       = isset($_GET['page'])       ? (int)$_GET['page']     : 0;
        $Gqtitlebody = isset($_GET['qtitlebody']) ? $_GET['qtitlebody']    : NULL;
        $Gtag        = isset($_GET['tag'])        ? $_GET['tag']           : NULL;

        $sort = Q::ini('appini/sort');

        // 准备分页新闻：$pagination
        $conditions = NULL;
        if($Gctgry_id != NULL)
        {
            $conditions = "category_id = {$Gctgry_id}";
        }
        $news = News::find($conditions)
            ->all()->order('news_id DESC')->limitPage($Gpage, 13)->fetchPagination($newspg)->get();

        // 处理新闻标题搜索
        $qtitlebodyrecords = array();
        if(CIB::_SQL_filter($Gqtitlebody))
        {
            $qtitlebodyrecords = News::find("title like ?", '%'.$Gqtitlebody.'%')
                ->orWhere('body like ?', '%'.$Gqtitlebody.'%')
                ->all()->order($sort)->query();
        }

        // 处理搜索结果：$tag
        $tagrecords = array();
        if(CIB::_SQL_filter($Gtag))
        {
            $tagrecords = News::find("[tag] like ?", '%'.$Gtag.'%')->all()->order($sort)->query();
        }

        $this->_view['qtitlebodyrecords'] = $qtitlebodyrecords;
        $this->_view['tagrecords']        = $tagrecords;

        $this->_view['news']     = $news;
        $this->_view['newspg']   = $newspg;

        $this->_view['cssfile'] = 'bonewsnotice.css';
    }
    /**
     * 新闻信息(Update)
     */
    public function actionEditNews()
    {
        $Pnews_id     = isset($_POST['news_id'])   ? $_POST['news_id']         : NULL;
        $Ptitle       = isset($_POST['title'])     ? $_POST['title']           : NULL;
        $Pbody        = isset($_POST['body'])      ? $_POST['body']            : NULL;
        $Ppublisher   = isset($_POST['publisher']) ? $_POST['publisher']       : NULL;
        $Pcategory_id = isset($_POST['ctgry_id'])  ? $_POST['ctgry_id']        : 11;
        $Psticky      = isset($_POST['sticky']) && $_POST['sticky'] == 0 ? 0   : 1;
        $Ptag         = isset($_POST['tag'])       ? $_POST['tag']             : NULL;
        $Pisprivate   = isset($_POST['isprivate']) && $_POST['isprivate'] == 0 ? 0 : 1;

        $Payear  = isset($_POST['ayear'])  ? $_POST['ayear']  : NULL;
        $Pamonth = isset($_POST['amonth']) ? $_POST['amonth'] : NULL;
        $Paday   = isset($_POST['aday'])   ? $_POST['aday']   : NULL;

        $PreserveAdate = isset($_POST['reserveAdate']) ? $_POST['reserveAdate'] : NULL; // 是否保持原有日期

        $Fattachments = isset($_FILES['attachment']) ? TRUE : FALSE;

        if($Ptitle && $Pbody && $Ppublisher && $Pcategory_id) // 太长条件写不下，与里面的if'与'关系
        {
            if(News::find('news_id = ?', $Pnews_id)->query()->news_id != '')
            {
                /**
                 *
                 * 先处理标签
                 * 先查出旧分类，删除标签 tag->counts - 1
                 * 再查出新分类，添加标签 tag->counts + 1
                 */
				
                $onews     = News::find('news_id = ?', $Pnews_id)->query();
                $octgry_id = $onews->category_id;
                $otag      = trim($onews->tag, ',');

                // 新闻通知版块是 ARRAY_MERGE getSubArray(4,7,8,23)
                $tag_category = NULL;
                if(in_array($octgry_id, NewsCategory::getSelfArrayId(array(4,7,8,23))) !== FALSE)
                {
                    $tag_category = '新闻通知';
                }
                elseif(in_array($octgry_id, NewsCategory::getSelfArrayId(81)) !== FALSE)
                {
                    $tag_category = '国际交流';
                }
                elseif(in_array($octgry_id, NewsCategory::getSelfArrayId(83)) !== FALSE)
                {
                    $tag_category = '创新实践';
                }

                if($tag_category != NULL)
                {
                    foreach(explode(',', $otag) as $v)
                    {
                        $obj = Tag::find('category = ? AND tag = ?', $tag_category, $v)->query();
                        if($obj->tag_id != '')
                        {
                            $obj->counts -= 1;
                            if($obj->counts == 0)
                            {
                                $obj->destroy();
                            }
                            else
                            {
                                $obj->save();
                            }
                        }
                    }
                }

                $tag_category = NULL;
                if(in_array($Pcategory_id, NewsCategory::getSelfArrayId(array(4,7,8,23))) !== FALSE)
                {
                    $tag_category = '新闻通知';
                }
                elseif(in_array($Pcategory_id, NewsCategory::getSelfArrayId(81)) !== FALSE)
                {
                    $tag_category = '国际交流';
                }
                elseif(in_array($Pcategory_id, NewsCategory::getSelfArrayId(83)) !== FALSE)
                {
                    $tag_category = '创新实践';
                }

                if($tag_category != NULL && $Ptag != '')
                {
                    foreach(explode(',', $Ptag) as $v)
                    {
                        $obj = Tag::find('category = ? AND tag = ?', $tag_category, $v)->query();
                        if($obj->tag_id == '')
                        {
                            $obj->category     = $tag_category;
                            $obj->tag          = $v;
                            $obj->counts       = 1;
                            $obj->isvisible    = 1;
                            $obj->isonhomepage = 0;
                            $obj->hit_as_query = 0;
                            $obj->save();
                        }
                        else
                        {
                            $obj->counts += 1;
                            $obj->save();
                        }
                    }
                }
				

                /**
                 * 处理其他 POST 值
                 *
                 */
            if(strpos($Pbody, '<div>') !== FALSE)
            {
               $Pbody = str_replace('<div>', '<p>', $Pbody);
            }
            if(strpos($Pbody, '</div>') !== FALSE)
            {
               $Pbody = str_replace('</div>', '</p>', $Pbody);
            }
            if(strpos($Pbody, '<br />') !== FALSE)
            {
               $Pbody = str_replace('<br />', '</p><p>', $Pbody);
            }
                $news = News::find('news_id = ?', $Pnews_id)->query();
                $news->title       = $Ptitle;
                $news->body        = $Pbody;
                $news->publisher   = $Ppublisher;
                $news->updated     = $_SERVER['REQUEST_TIME'];
                $news->category_id = $Pcategory_id;
                $news->tag         = ','.$Ptag.',';
                $news->sticky      = $Psticky;
                $news->isprivate   = $Pisprivate;

                if($PreserveAdate == NULL)
                {
                    $news->adate  = "20{$Payear}-{$Pamonth}-${Paday}";
                    $news->adated = strtotime($news->adate);
                }

                $news->save();
            }

            /**
             * 有内容"提交"后
             * 如果有附件，处理附件，更新 $attachment
             *
             * 第一步，处理文件本身
             * 第二步，处理数据表
             *
             * ($Fattachments == TRUE) 表示有附件上传
             */
            if($Fattachments)
            {
                // 此为表逻辑操作，应当被封装为如下语句
                //$notice = $this->_tdocs->uploadAttachment($_param1, $paramN);

                /**
                 * 定义允许上传的文件类型
                 * 可在数据库修改
                 * 'jpg,png,gif, doc,docx,ppt,pptx,xsl,xslx, txt,pdf, rar,zip,tgz'
                 */
                $allowExts     = Q::ini('appini/uploadAllowExts');

                /**
                 * NOTICE : 该值与PHP设置 {php.ini} 有关
                 * 定义允许上传的最大尺寸
                 * 可在数据库修改
                 * 10 * 1024 * 1024 (10M)
                 */
                $maxSize       = Q::ini('appini/uploadMaxSize');

                /**
                 * 定义允许 课件文件夹
                 * '../upload_attachment'
                 */
                $attachmentDir = Q::ini('appini/attachmentDir');

                $uploader      = new Helper_Uploader();
                $attachments   = $uploader->allfiles();

                foreach($attachments as $attachment)
                {
                    // 执行操作：移动文件
                    $attachmentid = md5($_SERVER['REQUEST_TIME'] . $attachment->filename());
                    $filename = urlencode($attachmentid . '.' . strtolower($attachment->extname()));
                    $attachment->move($attachmentDir."/{$filename}");

                    // 执行操作：保存文件映射记录
                    $newAttachmentRecord = new NewsAttachment(
                        array(
                            'path'     => $attachmentDir."/{$filename}",
                            'size'     => round($attachment->filesize() / 1024 / 1024 , 2).'M',
                            'type'     => $attachment->extname(),
                            'filename' => $attachment->filename(),
                            'news_id'  => $Pnews_id,
                    ));
                    $newAttachmentRecord->save();
                }

                // 显示列表
                return $this->_forward('bonewsnotice/listnews');
            }
        }
    }
    /**
     * 新闻信息(delete)
     * 有附件时一并删除
     * 有标签时一并删除
     */
    public function actionDeleteNews()
    {
        $Gnews_id = isset($_GET['news_id']) ? (int)$_GET['news_id'] : NULL;
        $news = News::find('news_id = ?', $Gnews_id)->query();

        if($Gnews_id && $news->title != '')
        {
            // 删除标签
            /**
             *
             * 先处理标签
             * 先查出旧分类，删除标签 tag->counts - 1
             * 再查出新分类，添加标签 tag->counts + 1
             */
            $octgry_id = $news->category_id;
            $otag      = trim($news->tag, ',');

            // 新闻通知版块是 ARRAY_MERGE getSubArray(4,7,8,23)
            $tag_category = NULL;
            if(in_array($octgry_id, NewsCategory::getSelfArrayId(array(4,7,8,23))) !== FALSE)
            {
                $tag_category = '新闻通知';
            }
            elseif(in_array($octgry_id, NewsCategory::getSelfArrayId(81)) !== FALSE)
            {
                $tag_category = '国际交流';
            }
            elseif(in_array($octgry_id, NewsCategory::getSelfArrayId(83)) !== FALSE)
            {
                $tag_category = '创新实践';
            }

            if($tag_category != NULL)
            {
                foreach(explode(',', $otag) as $v)
                {
                    $obj = Tag::find('category = ? AND tag = ?', $tag_category, $v)->query();
                    if($obj->tag_id != '')
                    {
                        $obj->counts -= 1;
                        if($obj->counts == 0)
                        {
                            $obj->destroy();
                        }
                        else
                        {
                            $obj->save();
                        }
                    }
                }
            }

            // 删除附件
            if(!$news->attachments->isEmpty())
            {
                foreach($news->attachments as $attachment)
                {
                    unlink($attachment->path);
                }
            }
            $news->destroy();
        }

        return $this->_forward('bonewsnotice/listnews');
    }

    /**
     * 新闻附件(Delete)
     */
    public function actionDeleteAttachment()
    {
        $attachment = NewsAttachment::find('attachment_id = ? AND news_id = ?', $_GET['attachment_id'], $_GET['news_id'])->query();

        if($attachment->attachment_id != '')
        {
            unlink($attachment->path); // 删除文件
            $attachment->destroy();    // 删除数据表数据
        }

        return $this->_redirect(url('bonewsnotice/editnews', array('news_id' => $_GET['news_id'])));

    }

    /**
     * 新闻分类(Read, Create)
     */
    public function actionAddNewsCtgry()
    {
        $Pcategory  = isset($_POST['new_ctgry'])  ? $_POST['new_ctgry'] : NULL;
        $Phaschild  = isset($_POST['haschild'])   ? $_POST['haschild']  : NULL;
        $Pparent_id = isset($_POST['parent_id'])  ? $_POST['parent_id'] : NULL;

        if($Pcategory && NewsCategory::find('category = ?', $Pcategory)->query()->id == '')
        {
            $newNewsCategoryRecord = new NewsCategory(
                array(
                    'category'  => $Pcategory,
                    'haschild'  => $Phaschild,
                    'parent_id' => $Pparent_id,
            ));
            $newNewsCategoryRecord->save();
        }

        $this->_view['cssfile'] = 'bonewsnotice.css';
    }
    /**
     * 新闻分类(Update)
     */
    public function actionEditNewsCtgry()
    {
        $Pid        = isset($_POST['id'])        ? $_POST['id']        : NULL;
        $Pcategory  = isset($_POST['category'])  ? $_POST['category']  : NULL;
        $Phaschild  = isset($_POST['haschild'])  ? $_POST['haschild']  : NULL;
        $Pparent_id = isset($_POST['parent_id']) ? $_POST['parent_id'] : NULL;

        if($Pid && $Pcategory && isset($Phaschild) && isset($Pparent_id))
        {
            if(NewsCategory::find('parent_id = ?', $Pid)->query()->id != '')
            {
                $Phaschild = 1;
            }
            $newsCtgry = NewsCategory::find('id = ?', $Pid)->query();
            $newsCtgry->category  = $Pcategory;
            $newsCtgry->haschild  = $Phaschild;
            $newsCtgry->parent_id = $Pparent_id;

            $newsCtgry->save();

            return $this->_forward('bonewsnotice/addnewsctgry');
        }
    }
    /**
     * 新闻分类(Delete)
     */
    public function actionDeleteNewsCtgry()
    {
        $Gid = isset($_GET['id']) ? $_GET['id'] : NULL;

        if($Gid && News::find('category_id = ?', $Gid)->query()->news_id == '')
        {
            NewsCategory::meta()->deleteWhere('id = ? AND haschild != 1', $Gid);
        }

        return $this->_forward('bonewsnotice/addnewsctgry');
    }
}